package pl.register.android.course.factory;

import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import pl.register.android.course.Course;
import roboguice.util.RoboAsyncTask;

public class AsyncNextCourseCreator extends RoboAsyncTask<Course> {
    private static final String TAG = AsyncNextCourseCreator.class.getSimpleName();

    private ProgressDialog progressDialog;

    private CreatorCourseMonitoring creatorCourseMonitoring;

    public AsyncNextCourseCreator(Context context, CreatorCourseMonitoring creatorCourseMonitoring) {
        super(context);
        this.creatorCourseMonitoring = creatorCourseMonitoring;

        progressDialog = new ProgressDialog(context);
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("Tworzenie kursu na następny rok. Proszę nie wyłączać aplikacji...");
    }

    @Override
    protected void onPreExecute() {
        progressDialog.show();
    }

    @Override
    public Course call() throws Exception {
        CourseFactory courseFactory = new CourseFactory(context);
        return courseFactory.insertCourseForNextYear();
    }

    @Override
    protected void onSuccess(Course result) {
        creatorCourseMonitoring.insertedNewCourse(result);
    }

    @Override
    protected void onFinally() {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onException(Exception exception) {
        try {
            throw exception;
        } catch (Exception e1) {
            Toast.makeText(getContext(), "Wystąpił nieoczekiwany problem podczas zczytywania danch.", Toast.LENGTH_SHORT).show();
            e1.printStackTrace();
        }
        Log.e(TAG, exception.getMessage(), exception);
    }

}